package testcases

import groovy.transform.CompileStatic
import io.micronaut.http.HttpRequest
import io.micronaut.http.HttpResponse
import io.micronaut.http.HttpStatus
import io.micronaut.http.MediaType
import io.micronaut.http.client.HttpClient
import org.junit.Assert
import org.junit.FixMethodOrder
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.MethodSorters
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.test.context.junit4.SpringRunner

@CompileStatic
@RunWith(SpringRunner)
@SpringBootTest(classes = Application, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
class AuthTestCases {

    static final String clientId = "app1serv"
    static final String clientSecret = "secret"
    static final String username = "openid123456"
    static final String password = "device-1234567890"

    static HttpClient authClient = HttpClient.create("http://localhost:8080".toURL())
    static HttpClient resClient = HttpClient.create("http://localhost:8081".toURL())

    @Test
    void test1() {
        HttpResponse<Map> resp1 = authClient.toBlocking().exchange(
                HttpRequest.POST("/oauth/token", ["grant_type": "password", username: username, password: password])
                        .accept(MediaType.APPLICATION_JSON_TYPE)
                        .basicAuth(clientId, clientSecret)
                        .contentType(MediaType.APPLICATION_FORM_URLENCODED_TYPE),
                Map)

        Assert.assertEquals(resp1.status, HttpStatus.OK)
        Assert.assertTrue(resp1.body.isPresent())

        def bearerToken = resp1.body().get("access_token")

        HttpResponse<String> resp2 = resClient.toBlocking().exchange(
                HttpRequest.GET("/hello/hi/testcases")
                        .accept(MediaType.TEXT_PLAIN_TYPE)
                        .bearerAuth(bearerToken as CharSequence),
                String)

        Assert.assertNotEquals(HttpStatus.UNAUTHORIZED, resp2.status())
        Assert.assertEquals(HttpStatus.OK, resp2.status())
        Assert.assertEquals("hello testcases", resp2.body())
    }
}
